<template>
	<view>
        <uni-nav-bar id="nav" class="u-f-ajc" :height="modelType == 'pad'?54:44" :statusBar="true" :fixed="true">
            <view slot="left"  style="width: 50px;" @click="backAction()">
                <uni-icons type="back" size="25"></uni-icons>
            </view>
            <view class="" style="width: 100%;" :style="{lineHeight: modelType == 'pad'?'54px':'44px'}">
                <template>
                    <view class="u-f-r u-f-ac u-f-ajc" style="width: 100%;">
                        <view class="navTitle" style="font-weight: 800">设备配置引导</view>
                    </view>
                </template>
            </view>
        </uni-nav-bar>
		<j-cell-group>
			<j-cell-card title="是否打开消息推送" :more="false">
				<view slot="tips" style="margin-right:20rpx;">
					<j-switch :disabled="disabled" v-model="isSubscribe" color="#FF0025" @change="switchChange" ></j-switch>
				</view>
			</j-cell-card>
		</j-cell-group>
		<view class="foot-button">
			<button class="block radius-btn" @tap="accomplish()" type="operation">完成</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				allDeviceList:[],
				disabled:false,
				isSubscribe:true,
				device:{
					deviceNo:'',
					token:'',
				},
				lat:0,//纬度
				lon:0,//经度
				connecttype: "", //配网类型
                modelType: null
			}
		},
		onLoad(options) {
			this.connecttype = options.connecttype
			let enData = decodeURIComponent(options.device)
			this.device = JSON.parse(enData)
			// this.getAllDeviceListByPage()
			this.getDeviceToken([this.device.deviceNo])
			console.log('获取设备信息====',this.device);
			this.getLocation()
		},
        onReady() {
            uni.getSystemInfo({
                success: (res) => {
                    console.log('系统信息', res);
                    this.modelType = res.deviceType;
                    let navHeight = this.modelType == 'pad' ? 54 : 44
                }
            });
        },
		methods: {
            backAction() {
                console.log('点击了返回')
                uni.showModal({
                    title: '提示',
                    content: '确认要结束配置？',
                    success: (res) => {
                        if(res.confirm) {
                            // 点击确定
                            console.log('返回首页', res)
                            uni.switchTab({
                                url:'/jvss/pages/device/home'
                            })

                        } else if(res.cancel) {
                            // 点击取消
                        }

                    },
                    fail: () => {}
                })
            },
			// 获取位置
			getLocation(){
				wx.getLocation({
					type: 'gcj02',
					success: (res) => {
						console.log('获取位置',res);
						
						this.lat = res.latitude
						this.lon = res.longitude
						this.setDeviceLocation()
					}
				})
			},
			//设置设备位置
			setDeviceLocation() {
			    const data = {
					sn:this.device.deviceNo,
					lat:this.lat,
					lon:this.lon,
				};
			    getApp().globalData.api.setDeviceLocation(data, (result) => {
			        console.log('设置经纬度:', result);
			    })
			},
			//开关
			switchChange(e) {
				console.log('开关==',e);
				this.disabled = true
				if(e){
					this.subscribeMsgNoticeServe()
				}else{
					this.cancelSubscribeMsgNoticeServe()
				}
			},
			// 查询所有设备列表
			getAllDeviceListByPage() {
			    const data = {};
			    getApp().globalData.api.getAllDeviceList(data, (result) => {
			        console.log('所有设备列表:', result);
					let sns = [];
					result.forEach((item)=>{
						if(!item.deviceNo.includes('vir')){
							this.allDeviceList.push(item)
							sns.push(item.deviceNo)
						}
					})
					if (sns.length > 0) {
					    this.getDeviceToken(sns);
					}
			    })
			},
			// 获取设备token
			getDeviceToken(sns) {
				const data = {
					sns: sns
				};
				getApp().globalData.api.getDeviceToken(data, (result) => {
					console.log('获取设备token:', result);
					// this.allDeviceList.forEach((item) => {
					// 	this.$set(item,'isSelected',false)
					//     result.forEach((pro) => {
					//         if (item.deviceNo === pro.sn) {
					//             item.token = pro.token;
					//         }
					// 		if(this.device.deviceNo === pro.sn){
					// 			this.device.token =  pro.token
					// 		}
					//     });
					// });
					// this.subscribeAllDevice(this.allDeviceList)
					this.device.token =  result[0].token
					this.subscribeMsgNoticeServe()
				});
			},
			// 订阅所有设备
			subscribeAllDevice(list){
				let subscribeList = []
				list.forEach((item)=>{
					subscribeList.push({
						sn:item.deviceNo,
						token:item.token
					})
				})
				let data = {
					subscribeList:subscribeList
				}
				getApp().globalData.api.subscribeAllDeviceBatchSubscribe(data, (result) => {
					this.getSubscribeStatus([this.device.deviceNo])
				    console.log('订阅设备:', result);
				    // console.log('deviceList ===',this.allDeviceList);
				});
			},
			//获取设备的订阅状态
			getSubscribeStatus(sns){
				let data = { sns:sns }
				getApp().globalData.api.getDeviceSubscribeStatus(data,(result)=>{
					console.log('获取订阅状态',result);
					this.isSubscribe = result[0].subscribed
					if(!this.isSubscribe){
						this.subscribeMsgNoticeServe()
					}
				})
			},
			// 订阅消息
			subscribeMsgNoticeServe() {
				let data = {
					sn: this.device.deviceNo,
					token: this.device.token,
				}
				getApp().globalData.api.subscribePMSMessage(data, (result) => {
					console.log('PMS订阅', result);
					if(result.data.code == 2000){
						console.log('PMS订阅成功', result);
						this.isSubscribe = true
						this.disabled = false
					}else{
						switch (this.connecttype){
							case 'qrcode':
								this.$postPointData({code:'401208', eventName:'qr_save_push_failed',reason:result.data.msg,error_code:result.data.code,action:'cancel'})
								break;
							case 'wifi':
								this.$postPointData({code:'401010', eventName:'wifi_save_push_failed',reason:result.data.msg,error_code:result.data.code,action:'cancel'})
								break;
							case 'bluetooth':
								this.$postPointData({code:'401111', eventName:'bluetooth_save_push_failed',reason:result.data.msg,error_code:result.data.code,action:'cancel'})
								break;
						}
					}
					
				},false,false);
			},
			//取消订阅
			cancelSubscribeMsgNoticeServe(item){
				let data = {
					sn: this.device.deviceNo,
					token: this.device.token,
				}
				getApp().globalData.api.cancelSubscribeMessage(data, (result) => {
					console.log('取消订阅', result);
					this.isSubscribe = false
					this.disabled = false
				});
			},
			//完成
			accomplish(){
				uni.setStorageSync('appIsShow',true)
				uni.switchTab({
					url:'/jvss/pages/device/home'
				})
			}

		}
	}
</script>

<style>

</style>
